# -*- coding: utf-8 -*-
# @Time    : 2023/8/19
# @Author  : Yangyali
#
import json

from loguru import logger
import yaml
import os
def read_yaml(key):
    """读取yaml文件"""
    filepath=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'\\extract.yml'

    with open(filepath, "r", encoding='utf-8') as file:
        try:
            data = yaml.safe_load(file)
            return data[key]
        except yaml.YAMLError as e:
            logger.info("YAML解析错误:", e)
    file.close()

def write_to_yaml(key,value):
    """写入yaml文件"""
    file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '\\extract.yml'
    logger.info(file_path)
    # # 读取原始YAML文件内容
    # with open(file_path, 'r') as file:
    #     try:
    #         existing_data = yaml.safe_load(file)
    #     except yaml.YAMLError as e:
    #         logger.info("YAML读取错误:", e)
    #         return
    #
    # # 添加新的键值对
    a={}
    a[key]=value

    # 写入更新后的数据到YAML文件
    with open(file_path, 'w') as file:

        try:
            yaml.dump(a, file)
            logger.info("YAML追加写入成功")
        except yaml.YAMLError as e:
            logger.info("YAML写入错误:", e)




def clear_yaml():
    # 使用空字典或空数据作为清空的内容
    empty_data = None  # 或 empty_data = None
    file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '\\extract.yml'
    # 写入空数据到YAML文件
    with open(file_path, 'w') as file:
        try:
            yaml.dump(empty_data, file)
            logger.info("YAML文件已清空")
        except yaml.YAMLError as e:
            logger.info("YAML写入错误:", e)


import configparser
def get_config_value(section,option):
    """获取config.ini中的环境配置"""
    cf = configparser.ConfigParser()
    filename = cf.read(r"D:\Project\API_autotest_playwright\config.ini")
    return cf.get(section, option)


def yaml_data(filename,case_name):
    """读取测试数据"""
    file_path = os.path.abspath(filename)
    print(file_path)
    with open(filename, "r") as f:
        if file_path.endswith((".yml", ".yaml")):
            data = yaml.load(f, Loader=yaml.FullLoader)
        elif file_path.endswith(("json")):
            data = json.load(f)
        else:
            print("文件类型错误，仅支持yaml和json")
            raise
    result = []
    for key, value in data.items():
        if key == case_name:
            case_data = []
            for k, v in value.items():

                case_data.append(v)
            result.append(tuple(case_data))
    print(result)

    return result

